import { createRouter, createWebHistory } from 'vue-router'

const routerHistorys = createWebHistory()

const router = createRouter({
  history: routerHistorys,
  routes: [
    {
      path: '/',
      component: () => import('@/pages/Index'),
      children: [
        {
          path: '',
          component: () => import('@/components/index/MyBody')
        }, {
          path: 'center',
          meta: {
            title: '个人中心',
            require: true
          },
          component: () => import('@/components/user/Center')
        }, {
          path: 'article/publish',
          meta: {
            title: '发表文章',
            require: true
          },
          component: () => import('@/components/article/Publish')
        }, {
          path: 'article',
          meta: {
            title: '文章列表'
          },
          component: () => import('@/components/article/Index')
        }, {
          path: 'article/detail/:id',
          meta: {
            title: '文章详情'
          },
          component: () => import('@/components/article/Detail')
        }
      ]
    }, {
      path: '/login',
      component: () => import('@/pages/Login')
    }, {
      path: '/password_reset',
      component: () => import('@/pages/PasswordReset')
    }
  ]
})
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  // 在跳转路由之前，先清除所有的请求
  if (to.meta.require) {
    const token = localStorage.getItem('mkcsa-token')
    if (!token || token === '') {
      router.push('/login')
    }
  }
  next()
})

export default router
